<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户账号">
          <el-input v-model="searchForm.LoginName" placeholder="请输入用户账号" clearable />
        </el-form-item>
        <el-form-item label="会员等级">
          <el-select v-model="searchForm.VipLevel" placeholder="请选择会员等级" clearable style="width: 150px;">
            <el-option label="所有会员" :value="0" />
            <el-option label="白银会员" :value="1" />
            <el-option label="黄金会员" :value="2" />
            <el-option label="钻石会员" :value="3" />
            <el-option label="至尊会员" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
          <el-button>
            <a href="http://localhost:5161/api/Export/ExportExcel">导出</a>
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <!-- <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增用户
          </el-button> -->
        </div>
      </template>

      <el-table 
        :data="tableData" 
        style="width: 100%"
        border
        stripe
        highlight-current-row
        v-loading="loading"
      >
        <el-table-column fixed prop="AccountId" label="Id编号" width="100" />
        <el-table-column prop="LoginName" label="用户账号" width="150" />
        <el-table-column prop="VipLevel" label="会员等级" width="120">
          <template #default="{ row }">
            <el-tag :type="getVipLevelType(row.VipLevel)">
              {{ getVipLevelText(row.VipLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="Status" label="用户状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.Status === 1 ? 'danger' : 'success'">
              {{ row.Status === 0 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="AccountList" label="订单记录" width="120" />
        <el-table-column prop="AccountPay" label="消费金额" width="120">
          <template #default="{ row }">
            ¥{{ row.AccountPay?.toFixed(2) || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="AccountStore" label="可用积分" width="120" />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleDetail(row)">
              <el-icon><View /></el-icon>详情
            </el-button>
            <el-button link type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row.AccountId)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="LookData.PageIndex"
          v-model:page-size="LookData.PageSize"
          :page-sizes="[5, 10, 20, 30]"
          :total="LookData.TotalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="用户详情" width="500px">
      <el-form label-width="100px">
        <el-form-item label="用户账号">
          <el-input :model-value="displayValue(currentUserDetail.LoginName)" disabled />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input :model-value="displayValue(currentUserDetail.AccountTel)" disabled />
        </el-form-item>
        <el-form-item label="会员等级">
           <el-input :model-value="displayValue(getVipLevelText(currentUserDetail.VipLevel))" disabled />
        </el-form-item>
         <el-form-item label="生日">
          <el-input :model-value="displayValue(currentUserDetail.Birthday ? new Date(currentUserDetail.Birthday).toLocaleDateString() : null)" disabled />
        </el-form-item>
        <el-form-item label="所在城市">
          <el-input :model-value="displayValue(currentUserDetail.AddrCity)" disabled />
        </el-form-item>
        <el-form-item label="职业">
          <el-input :model-value="displayValue(currentUserDetail.AccountJob)" disabled />
        </el-form-item>
        <el-form-item label="个性签名">
          <el-input type="textarea" :model-value="displayValue(currentUserDetail.Signature)" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改资料对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改资料" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="用户账号">
          <el-input v-model="editForm.LoginName" disabled />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="editForm.AccountTel" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="会员等级">
          <el-radio-group v-model="editForm.VipLevel">
            <el-radio-button :label="0">普通会员</el-radio-button>
            <el-radio-button :label="1">白银会员</el-radio-button>
            <el-radio-button :label="2">黄金会员</el-radio-button>
            <el-radio-button :label="3">钻石会员</el-radio-button>
            <el-radio-button :label="4">至尊会员</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日">
           <el-date-picker
            v-model="editForm.Birthday"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="所在城市">
          <el-input v-model="editForm.AddrCity" placeholder="请输入所在城市" />
        </el-form-item>
        <el-form-item label="职业">
          <el-input v-model="editForm.AccountJob" placeholder="请输入职业" />
        </el-form-item>
         <el-form-item label="个性签名">
          <el-input v-model="editForm.Signature" type="textarea" placeholder="请输入个性签名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { GetAccountList } from '@/api/Readapi'
import { ElMessage, ElMessageBox, ElDialog, ElForm, ElFormItem, ElInput, ElRadioGroup, ElRadioButton, ElDatePicker, ElSelect, ElOption, ElTag } from 'element-plus'
import { Search, Refresh, View, Edit, Delete } from '@element-plus/icons-vue'
import { DelAccount, UpdateAccount } from '@/api/Writeapi'

const loading = ref(false)
const tableData = ref([])

onMounted(()=>{
  GetData();
})

const searchForm = reactive({
  LoginName: '',
  VipLevel: 0
})

const LookData = reactive({
  PageIndex: 1,
  PageSize: 10,
  LoginName: '',
  AccountTel: '',
  VipLevel: 0,
  TotalCount: 0,
  TotalPage: 0
})

const detailDialogVisible = ref(false)
const currentUserDetail = ref<any>({}) // 用于存储当前查看详情的用户数据

const editDialogVisible = ref(false) // 控制修改对话框显示状态
const editForm = reactive<any>({ // 存储当前编辑的用户数据
    AccountId: 0,
    LoginName: '',
    AccountTel: '',
    VipLevel: 0,
    Birthday: '',
    AddrCity: '',
    AccountJob: '',
    Signature: '',
}) as any; // 使用 any 绕过类型检查，实际项目中应定义接口

// Function to display "空值" if value is null, undefined, or empty string
const displayValue = (value: any) => {
  if (value === null || value === undefined || value === '' || (typeof value === 'number' && isNaN(value)) ) {
    return ''; // 在编辑框中空值显示为空白
  }
   if (typeof value === 'boolean') {
    return value ? '是' : '否';
  }
  return value;
};

// 获取会员等级显示文本
const getVipLevelText = (level: number): string => {
  const levels: Record<number, string> = {
    0: '普通会员',
    1: '白银会员',
    2: '黄金会员',
    3: '钻石会员',
    4: '至尊会员'
  }
  return levels[level] || '未知等级'
}

// 获取会员等级标签类型
const getVipLevelType = (level: number): 'success' | 'info' | 'warning' | 'primary' | 'danger' => {
  const types: Record<number, 'success' | 'info' | 'warning' | 'primary' | 'danger'> = {
    0: 'info',      // 灰色
    1: 'warning',   // 黄色
    2: 'success',   // 绿色
    3: 'primary',   // 蓝色
    4: 'danger'     // 红色
  }
  return types[level] || 'info'
}

// 搜索
const handleSearch = () => {
  LookData.PageIndex = 1
  LookData.LoginName = searchForm.LoginName
  LookData.VipLevel = searchForm.VipLevel
  GetData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.LoginName = ''
  searchForm.VipLevel = 0
  handleSearch()
}

// 获取数据
const GetData = async () => {
  try {
    loading.value = true
    const res = await GetAccountList({
      PageIndex: LookData.PageIndex,
      PageSize: LookData.PageSize,
      LoginName: LookData.LoginName,
      AccountTel: LookData.AccountTel,
      VipLevel: LookData.VipLevel,
    })
    tableData.value = res.data.data;
    LookData.TotalCount = res.data.TotalCount;
    LookData.TotalPage = res.data.TotalPage;

  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

//改变页容量
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  LookData.PageSize=val
  GetData();
}
//改变页码
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  LookData.PageIndex=val;
  GetData();
}

// 查看详情
const handleDetail = (row: any) => {
  currentUserDetail.value = row; // 将当前行数据赋值给详情数据
  detailDialogVisible.value = true; // 打开对话框
}

// 编辑用户
const handleEdit = (row: any) => {
  // 将当前行数据复制到编辑表单
  Object.assign(editForm, row);
   // 处理可能的日期格式问题，如果 Birthday 是字符串，尝试转换为 Date 对象
  if (editForm.Birthday && typeof editForm.Birthday === 'string') {
      editForm.Birthday = new Date(editForm.Birthday);
  }
  editDialogVisible.value = true; // 打开对话框
}

interface ApiResponse {
  code: number
  msg: string
  data: any
}

// 保存修改
const handleSave = async () => {
    try {
        // 可以在这里添加表单验证
        // await editFormRef.value.validate();

        // 准备要发送到后端的数据
        const dataToSave = {
            AccountId: editForm.AccountId,
            AccountTel: editForm.AccountTel,
            VipLevel: editForm.VipLevel,
            // 将 Birthday 格式化为 YYYY-MM-DD，并构建 ISO 字符串，时间部分为零
            Birthday: editForm.Birthday,
            AddrCity: editForm.AddrCity,
            AccountJob: editForm.AccountJob,
            Signature: editForm.Signature,
        };

        const res = await UpdateAccount(dataToSave)as unknown as ApiResponse;
        console.log('Update response:', res);

        if (res.code === 200) { // 假设后端成功状态码是 200
            ElMessage.success('修改成功');
            editDialogVisible.value = false; // 关闭对话框
            GetData(); // 刷新列表
        } else {
            ElMessage.error(res.msg);
        }
    } catch (error) {
        console.error('保存修改失败:', error);
        ElMessage.error('保存修改失败');
    }
}

// 删除用户
const handleDelete = (id: any) => {
  ElMessageBox.confirm(
    `确定要删除用户吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async() => {
    await DelAccount(id);
    ElMessage.success('删除成功');
    GetData();
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

onMounted(() => {
  GetData()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-button) {
  margin-left: 8px;
}

:deep(.el-button:first-child) {
  margin-left: 0;
}

/* 自定义会员等级单选按钮样式 */
:deep(.el-radio-button__inner) {
  border: 1px solid #dcdfe6 !important;
  border-left: 0px !important; /* 移除左侧边框，让按钮紧密排列 */
  margin: 0 2px; /* 增加一点间距 */
  border-radius: 4px; /* 添加圆角 */
  padding: 8px 15px; /* 调整内边距 */
}

:deep(.el-radio-button__inner:first-child) {
     border-left: 1px solid #dcdfe6 !important;
}

:deep(.el-radio-button__inner.is-active) {
  color: #fff !important;
  background-color: #409eff !important; /* Element Plus Primary 颜色 */
  border-color: #409eff !important;
  box-shadow: -1px 0 0 0 #409eff; /* 确保选中时边框完整 */
}

:deep(.el-radio-button__orig-radio:checked+.el-radio-button__inner) {
     box-shadow: -1px 0 0 0 #409eff; /* 确保选中时边框完整 */
}

</style>
  